package com.briup.estore.web.servlet;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradePayModel;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.briup.estore.util.AlipayConfig;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/alipay")
public class AliPayServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 新建alipay客户端
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipaydev.com/gateway.do", AlipayConfig.APP_ID,
                AlipayConfig.APP_PRIVATE_KEY, "json", AlipayConfig.CHARSET, AlipayConfig.ALIPAY_PUBLIC_KEY, "RSA2");
        //实例化具体API对应的request类
        AlipayTradePagePayRequest alireq = new AlipayTradePagePayRequest();
        //SDK已经封装掉了公共参数，这⾥只需要传⼊业务参数
        AlipayTradePayModel model = new AlipayTradePayModel();
        // 下⾯的设置都可以设置为参数值，这⾥为了测试全部写死
        // 订单编号
        model.setOutTradeNo("44156");
        // 订单⾦额
        model.setTotalAmount("100.00");
        // 订单名称
        model.setSubject("书籍订单");
        // 订单描述
        model.setBody(System.currentTimeMillis() + "");
        // 产品码
        model.setProductCode("FAST_INSTANT_TRADE_PAY");
        // 参数注⼊
        alireq.setBizModel(model);
        // 设置回调地址
        alireq.setReturnUrl("http://localhost:8989/estore/index_data");
        // 获得结果
        String result = "";
        try {
            result = alipayClient.pageExecute(alireq).getBody();
        } catch (AlipayApiException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        // 输出结果
        resp.setContentType("text/html;charset=utf - 8");
        resp.getWriter().println(result);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
